<?php

namespace app\commands;

use yii\console\Controller;

class SwooleController extends Controller
{
    public $server;

    public function actionRun()
    {
        $this->server = new \swoole_server('0.0.0.0', 39500);

        $this->server->set([
            'worker_num' => 4, //同时4进程异步
            'task_worker_num' => 100, //每个异步分发16个进程任务
            'daemonize' => false,
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'debug_mode' => 1,
        ]);

        $this->server->on('Start', [$this, 'onStart']);
        $this->server->on('Connect', [$this, 'onConnect']);
        $this->server->on('Receive', [$this, 'onReceive']);
        $this->server->on('Task', [$this, 'onTask']);
        $this->server->on('Close', [$this, 'onClose']);

        $this->server->start();
    }

    public function onStart()
    {

    }

    public function onConnect($server, $descriptors, $fromId)
    {

    }

    public function onReceive(\swoole_server $server, $descriptors, $fromId, $data)
    {
        echo '接收到 ' . date('H:i:s') . PHP_EOL;
        $server->task('邮件1');
        $server->task('邮件2');
    }

    public function onTask($server, $fd, $from_id, $data)
    {
        $this->sendMail($data);
        echo $data.' 邮件发送成功 ' . date('H:i:s') . PHP_EOL;
    }

    public function onClose($server, $descriptors, $fromId)
    {

    }

    public function SendMail($data)
    {
        \Yii::$app->mailer->compose()->setTo('574368565@qq.com')->setSubject("swoole测试邮件")->setTextBody($data)->send();
    }
}